package com.hafu.swing;

import com.hafu.model.Course;
import com.hafu.service.CourseService;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.List;

// 学生主界面框架
public class StudentMainFrame extends JFrame {
    private String studentId;
    private CourseService courseService = new CourseService();

    public StudentMainFrame(String studentId) {
        this.studentId = studentId;
        setTitle("学生主界面");
        setSize(600, 400);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLayout(new BorderLayout());

        // 课程列表
        JList<Course> courseList = new JList<>();
        updateCourseList(courseList);

        JButton studyButton = new JButton("开始学习");
        studyButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                Course selectedCourse = courseList.getSelectedValue();
                if (selectedCourse != null) {
                    try {
                        new StudyFrame(studentId, Integer.parseInt(selectedCourse.getCourseId()));
                    } catch (NumberFormatException ex) {
                        JOptionPane.showMessageDialog(StudentMainFrame.this, "课程ID格式错误", "错误", JOptionPane.ERROR_MESSAGE);
                    }
                }
            }
        });

        JPanel buttonPanel = new JPanel();
        buttonPanel.add(studyButton);

        add(new JScrollPane(courseList), BorderLayout.CENTER);
        add(buttonPanel, BorderLayout.SOUTH);

        setLocationRelativeTo(null);
        setVisible(true);
    }

    // 更新课程列表
    private void updateCourseList(JList<Course> courseList) {
        List<Course> courses = courseService.getCoursesByStudentId(studentId);
        courseList.setListData(courses.toArray(new Course[0]));
    }
}